package cn.jishiyu11.xeqb.activity

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentTransaction
import android.view.*
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast

import com.igexin.sdk.PushManager
import com.meiqia.core.MQManager
import com.umeng.analytics.MobclickAgent

import java.util.ArrayList
import java.util.Timer
import java.util.TimerTask

import cn.jishiyu11.xeqb.R
import cn.jishiyu11.xeqb.activity.personalCenterActivitys.MessageCenter
import cn.jishiyu11.xeqb.base.BaseActivity
import cn.jishiyu11.xeqb.base.BaseActivityManager
import cn.jishiyu11.xeqb.fragment.BaseNewsFragment
import cn.jishiyu11.xeqb.fragment.PersonalCenter_Fragment
import cn.jishiyu11.xeqb.http.http.i.httpbase.HOME_MOCK_URL
import cn.jishiyu11.xeqb.service.DemoIntentService
import cn.jishiyu11.xeqb.service.DemoPushService
import cn.jishiyu11.xeqb.utils.*
import cn.jishiyu11.xeqb.utils.CameraUtils.UserCenterRealize
import cn.jishiyu11.xeqb.view.MainActivityView
import cn.jishiyu11.xeqb.webview.X5WebViewActivity
import kotlinx.android.synthetic.main.activity_main.*

/**
 * create by jsy_zj
 * 2017-6-23
 * 基础主类
 */
class MainActivity : BaseActivity(), MainActivityView.OnItemClickListener{

    private var activity: Activity? = null
    private var mainActivityView: MainActivityView? = null

    private val titles = intArrayOf(R.string.name_first_fm, R.string.name_loanmoney_fm, R.string.name_docard_fm, R.string.name_personal_center)
    private val unSelectedImage = intArrayOf(R.mipmap.ic_loan_dark, R.mipmap.ic_quickcrd_dark, R.mipmap.ic_loansupermarket_dark, R.mipmap.ic_personalcenter_dark)
    private val selectedImage = intArrayOf(R.mipmap.ic_loan_brightness, R.mipmap.ic_quickcard_brightness, R.mipmap.ic_loansupermarket_brightness, R.mipmap.ic_personalcenter_brightness)

    private var mHeight: Int = 0
    private var isGetHeight = true

    private var mSelectPosition = 0

    private var listfragment:MutableList<Fragment?> = ArrayList<Fragment?>()

    private var listnewftagment:MutableList<Fragment> = ArrayList<Fragment>()

    private var userCenterRealize: UserCenterRealize? = null

    private var vt: ViewTreeObserver? = null

    private val demopushService = DemoPushService::class.java
    private val demoIntentPushService = DemoIntentService::class.java
    private var appkey: String? = ""
    private var appsecret: String? = ""
    private var appid: String? = ""

    private var homeUrl = ""
    private var loanUrl = ""
    private var docardUrl = ""

    private var snackBar:Snackbar? = null

    /**
     * 连续按两次返回键就退出
     */
    private var keyBackClickCount = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.activity = this
        userCenterRealize = UserCenterRealize()
        setContentView(R.layout.activity_main)
        mainActivity = this

        homeUrl = HOME_MOCK_URL + AppUtil.getInstance().getVersionName(1, this) + "&columnID=1"
        loanUrl = HOME_MOCK_URL + AppUtil.getInstance().getVersionName(1, this) + "&columnID=2"
        docardUrl = HOME_MOCK_URL + AppUtil.getInstance().getVersionName(1, this) + "&columnID=3"

        findViewById()

        val url = intent.getStringExtra("url") + ""
        if (url !== "" && !url.isEmpty() && url != "null") {
            val intent = Intent(this@MainActivity, X5WebViewActivity::class.java)
            intent.putExtra("url", url)
            startActivity(intent)
        }


        PushManager.getInstance().initialize(this.applicationContext, demopushService)
        PushManager.getInstance().registerPushIntentService(this.applicationContext, demoIntentPushService)
        parseManifests()
        //        getCid();
//        MQManager.getInstance(this).openMeiqiaService()
    }

    override fun findViewById() {
        val position = intent.getIntExtra("selectPosition", -1)
        if (position == -1) {
            mSelectPosition = 0
        } else {
            mSelectPosition = position
        }
        initView()

        if (position == -1) {
        } else {
            showFragment(position)
        }
        SharedPreferencesUtils.put(activity, this.getString(R.string.STATUS_FONT_COLOR), "WHITE")
    }

    override fun initView() {
        for (i in 0..3) {
            listfragment.add(null)
        }
        listnewftagment.add(BaseNewsFragment(homeUrl, "HOME_FRG_DATA", false, this.getString(R.string.name_first_fm)))
        listnewftagment.add(BaseNewsFragment(loanUrl, "LOAN_FRG_DATA", true, this.getString(R.string.name_loanmoney_fm)))
        listnewftagment.add(BaseNewsFragment(docardUrl, "DOCARD_FRG_DATA", true, this.getString(R.string.name_docard_fm)))
        listnewftagment.add(PersonalCenter_Fragment())

        // 获取屏幕宽度
        val dm = windowManager.defaultDisplay
        val screenWith = dm.width
        mainActivityView = findViewById(R.id.act_main_tab)
        // 初始化获取底部导航自身高度
        vt = mainActivityView!!.viewTreeObserver
        vt!!.addOnPreDrawListener {
            if (isGetHeight) {
                mHeight = mainActivityView!!.height
                mainActivityView!!.setLayout(titles, selectedImage, unSelectedImage, screenWith, mHeight, this@MainActivity)
                mainActivityView!!.setColorLing(mSelectPosition)
                mainActivityView!!.setOnItemClickListener(this@MainActivity)
                isGetHeight = false
            }
            true
        }
        showFragment(mSelectPosition)
    }

    override fun onItemClick(position: Int) {
        if (position==3 && USER_UserNo.isNullOrEmpty()){
            newIntent<LogoActivity>()
            showSwichFragment(0)
        }else{
//            var customToast = ToastUtilCustom(this,R.layout.toast_buttom_custom_layout,"自定义Toast",object :ToastClickListener{
//                override fun OnToastClick(view: View) {
//                    newIntent<AboutUsActivity>()
//                }
//            })
//            customToast.show()

//            initSnackBar()
            showFragment(position)

        }
    }

    /**
     * 动态添加和显示fragment
     * @param position
     */
     fun showFragment(position: Int) {


        val fm = supportFragmentManager
        val transaction = fm.beginTransaction()
        hideFragment(transaction)
        for (i in 0 until listfragment.size) {
            if (position == i) {
                if (listfragment[i] == null) {
                    listfragment.removeAt(i)
                    listfragment.add(i, listnewftagment[i])
                    if (!listnewftagment[i].isAdded) {
                        transaction.add(R.id.cat_main_fragment_content, listfragment[i])
                    } else {
                        transaction.show(listfragment[i])
                    }
                } else {
                    transaction.show(listfragment[i])
                }
                //fragment首页和我的页状态栏字体颜色为白色
                SharedPreferencesUtils.put(activity, this.getString(R.string.STATUS_FONT_COLOR), "WHITE")
            }
        }
        transaction.commitAllowingStateLoss()
    }

    /**
     * @author jsy_zj
     * created at 2017/11/27 15:46
     * 方法说明：设置fragment
     */
    fun showSwichFragment(position: Int) {
        if (position==3 && USER_UserNo.isNullOrEmpty()){
            newIntent<LogoActivity>()
        }else{
            showFragment(position)
            mainActivityView!!.setColorLing(position)
        }
    }

    /**
     * @author jsy_zj
     * created at 2017/12/7 10:39
     * 方法说明：个推信息，APPID和pushkey
     */
    private fun parseManifests() {
        val packageName = applicationContext.packageName
        try {
            val appInfo = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA)
            if (appInfo.metaData != null) {
                appid = appInfo.metaData.getString("PUSH_APPID")
                appsecret = appInfo.metaData.getString("PUSH_APPSECRET")
                appkey = appInfo.metaData.getString("PUSH_APPKEY")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    private fun getCid() {
        val cid = PushManager.getInstance().getClientid(this)
        Toast.makeText(this, resources.getString(R.string.show_cid) + cid, Toast.LENGTH_LONG).show()
    }

    /**
     * 隐藏所有fragment
     *
     * @param transaction
     */
    private fun hideFragment(transaction: FragmentTransaction) {
        for (i in 0 until listfragment.size) {
            if (listfragment[i] != null) {
                transaction.hide(listfragment[i])
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            when (keyBackClickCount++) {

                0 -> {

                    this.showShortToast("再按一次退出")
                    val timer = Timer()
                    timer.schedule(object : TimerTask() {
                        override fun run() {
                            keyBackClickCount = 0
                        }
                    }, 3000)
                }
                1 -> {
                    BaseActivityManager.activityManager.finishAllActivity()
                    finish()
                }
                else -> {
                }
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onResume() {
        super.onResume()
        MobclickAgent.onResume(this)
        USER_PhoneNo = SharedPreferencesUtils.get(this,getString(R.string.phoneNo),"").toString()
        USER_UserNo = SharedPreferencesUtils.get(this,getString(R.string.userNo),"").toString()
        USER_INVICEDCODE = SharedPreferencesUtils.get(this,getString(R.string.inviteCode),"").toString()
    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPause(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        println("mainAcivity  ===========  destroy")

        MQManager.getInstance(this@MainActivity).closeMeiqiaService()
    }

    private fun initSnackBar() {
        snackBar =   Snackbar.make(cat_main_fragment_content,"", Snackbar.LENGTH_LONG)
        customStyleSnackBar(snackBar!!,R.layout.view_snackbar_msg_layout,0,"这是标题党","我这里才是内容，是不是很意外，哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈！！")
        snackBar!!.show()
    }


    private fun customStyleSnackBar(snackbar: Snackbar,addLayoutInt:Int,index:Int,titles:String,contents:String){
        var snackbarView = snackBar?.getView();//获取SnackBar布局View实例
        var textView = (snackbarView?.findViewById<TextView>(R.id.snackbar_text));//获取文本View实例

        var snackbarLayout = snackbarView as Snackbar.SnackbarLayout
        var add_view = LayoutInflater.from(activity).inflate(addLayoutInt,null)
        add_view.setOnClickListener {
            newIntent<MessageCenter>()
            snackbar.dismiss()
        }
        var title = add_view.findViewById<TextView>(R.id.snackbar_title)
        title.text = titles
        title.setTextColor(Color.WHITE)
        var content = add_view.findViewById<TextView>(R.id.snackbar_content)
        content.text = contents
        content.setTextColor(Color.WHITE)

        var  p = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT)
        p.gravity = Gravity.CENTER
        snackbarLayout.addView(add_view,index,p)
//        snackbarView.setBackgroundColor(resources.getColor(R.color.common_gray))
        snackbarView.background = null
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
//        var intentResult = IntentIntegrator.parseActivityResult(requestCode,resultCode,data)
//        if (intentResult!=null){
//            if (intentResult.contents == null){
//                this.showShortToast("内容为空")
//            }else{
////                this.showShortToast("扫描成功")
//                var resule = intentResult.contents
//                this.showLongToast(resule)
//            }
//        }else{
//            super.onActivityResult(requestCode,resultCode,data)
//        }

    }


}
